<template>
  <div class="post-authorization">
    <p
      ref="title"
      class="title"> {{ title }} </p>
    <div class="post-box">
      <!-- 左边导航 -->
      <div
        v-loading="postMenuLoading"
        class="nav">
        <div class="nav-new-btn">
          <el-button
            size="medium"
            @click="newPostBtn"> 新建岗位 </el-button>
        </div>
        <el-input
          style="padding: 5px 10px"
          placeholder="请输入内容"
          prefix-icon="el-icon-search"
          v-model="postName"
          @keydown.enter.native="searchPost">
        </el-input>
        <!-- 角色列表 -->
        <div class="post-nav-box">
          <div
            v-for="(item, index) in postList"
            :key="index"
            :class="{'item-list-hover' : item.postId == postActive.postId}"
            class="item-list"
            @click="postMenuSelect(item)">
            {{ item.name }}
            <div
              v-if="item.remark != 'admin' && item.remark != 'project'"
              class="icon-close">
              <el-dropdown
                trigger="click"
                @command="postHandleClick">
                <i
                  class="el-icon-arrow-down"
                  @click="postDropdownClick(item)"/>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="edit">编辑</el-dropdown-item>
                  <el-dropdown-item command="delete">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>

      <!-- 岗位编辑 -->
      <el-dialog
        :title="postTitle"
        :visible.sync="newPostVisible"
        :before-close="newPostClose"
        width="30%">
        <label v-if="postTitle != '关联角色'" class="label-title">岗位名称</label>
        <el-input
          v-if="postTitle != '关联角色'"
          v-model="post.title"
          class="input-post"/>
        <label class="label-title">关联角色</label>
        <el-select v-model="AssociaRole" multiple placeholder="请选择" class="input-post">
          <el-option-group
            v-for="group in roleAllList"
            :key="group.name"
            :label="group.name">
            <el-option
              v-for="item in group.list"
              :key="item.id"
              :label="item.title"
              :value="item.id">
            </el-option>
          </el-option-group>
        </el-select>
        <span
          slot="footer"
          class="dialog-footer">
          <el-button
            type="primary"
            @click="newPostSubmit">确 定</el-button>
          <el-button @click="newPostClose">取 消</el-button>
        </span>
      </el-dialog>

      <!-- 右边内容 -->
      <div class="content-box">
        <el-tabs v-model="mainMenuIndex">
          <el-tab-pane
            label="岗位角色"
            name="user">
            <div
              v-loading="roleLoading"
              class="content-table">
              <flexbox class="content-table-header">
                <div class="content-table-header-reminder">
                  <reminder
                    v-if="showReminder"
                    :content="getReminderContent()"/>
                </div>
                <el-button
                  size="medium"
                  type="primary"
                  @click="newPostBtn('relatierol')"> 关联角色 </el-button>
              </flexbox>
              <el-table
                :data="tableData"
                :height="tableHeight"
                style="width: 100%">
                <el-table-column
                  v-for="(item, index) in tableList"
                  :prop="item.field"
                  :label="item.label"
                  :key="index"
                  show-overflow-tooltip>
                  <template
                    slot="header"
                    slot-scope="scope">
                    <div class="table-head-name" :title="scope.column.label">{{ scope.column.label }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <!-- <span class="el-icon-edit content-table-span"
                      @click="editBtn(scope.row)"></span> -->
                    <span
                      class="el-icon-delete content-table-span"
                      @click="roleDelect(scope.row)"/>
                  </template>
                </el-table-column>
              </el-table>
              <div class="p-contianer">
                <el-pagination
                  :current-page="currentPage"
                  :page-sizes="pageSizes"
                  :page-size.sync="pageSize"
                  :total="total"
                  class="p-bar"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"/>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!-- 关联员工 -->
    <relate-empoyee
      :visible.sync="relateEmpoyeeShow"
      :post-id="postId"
      @save="employeesSave"/>
  </div>
</template>

<script>
import RelateEmpoyee from './components/relateEmpoyee'
import Reminder from '@/components/reminder'
import {
  postListFun,
  roleByPostId,
  addAndSetPost,
  getPostByRoleId,
  deletePost,
  saveModifyPostRole,
  deleteRole
} from '@/api/systemManagement/post'
import { roleListFun } from '@/api/systemManagement/RoleAuthorization'

export default {
  components: {
    RelateEmpoyee,
    Reminder
  },

  data() {
    return {
      pid: '',
      title: '岗位管理',
      tableData: [], // 与角色关联的员工
      tableHeight: document.documentElement.clientHeight - 305, // 表的高度
      treeHeight: document.documentElement.clientHeight - 230, // 表的3度
      currentPage: 1,
      pageSize: 15,
      pageSizes: [15, 30, 45, 60],
      total: 0,
      tableList: [
        { label: '角色名称', field: 'name' },
        { label: '角色模块', field: 'moduleName' }
      ],

      // 新建角色
      newPostVisible: false,
      post: {}, // 操作角色的框 关联的信息
      postList: [], // 岗位列表 list属性 是信息

      mainMenuIndex: 'user', // 角色员工  角色权限 切换 默认左边
      // 权限管理
      ruleMenuIndex: 'data', // 默认模块 工作台
      ruleMenuList: [],
      defaultProps: {
        children: 'childMenu',
        label: 'menuName'
      },
      relateEmpoyeeShow: false,
      // 选中的角色
      postActive: null,
      dropdownHandlePost: null, // 下拉操作编辑角色
      // 新建编辑角色title
      postTitle: '',
      //   加载
      postMenuLoading: false,
      // 岗位加载中
      postLoading: false,
      // 角色列表加载中
      roleLoading: false,
      // 角色所有列表加载中
      roleAllLoading: false,
      // 关联角色
      postName: '',
      roleAllList: [],
      AssociaRole: []
    }
  },

  computed: {
    postId() {
      if (this.postActive) {
        return this.postActive.postId
      }
      return ''
    },
    // 展示提示问题
    showReminder() {
      if (this.postActive) {
        return this.postActive.remark == 'project'
      }

      return false
    }
  },

  watch: {},

  mounted() {
    /** 控制table的高度 */
    window.onresize = () => {
      this.tableHeight = document.documentElement.clientHeight - 305
      this.treeHeight = document.documentElement.clientHeight - 230
    }
    /** 获取权限信息 */
    this.pid = this.$route.params.pid
    this.getRoleList()
    this.getPostList()
  },

  beforeRouteUpdate(to, from, next) {
    this.pid = to.params.pid
    this.postActive = null
    this.postList = []
    this.currentPage = 1
    this.total = 0
    this.tableData = []
    // this.getPostList()
    next()
  },

  methods: {
    // 岗位编辑时获取角色
    editGetRoleId(data) {
      this.AssociaRole = []
      getPostByRoleId({
        postId: data.postId
      })
        .then(res => {
          for (var i = 0; i < res.data.roles.length; i++) {
            this.AssociaRole.push(res.data.roles[i].roleId)
          }
        })
        .catch(() => {
        })
    },
    // 获取所有的角色数据列表
    getRoleList() {
      this.roleAllLoading = true
      roleListFun()
        .then(res => {
          this.roleAllList = res.data
          this.roleAllLoading = false
        })
        .catch(() => {
          this.roleAllLoading = false
        })
    },
    // 查询
    searchPost() {
      this.postActive = ''
      this.getPostList()
    },
    /**
     * 获取岗位列表
     */
    getPostList() {
      this.postMenuLoading = true
      postListFun({ name: this.postName })
        .then(res => {
          this.postList = res.data
          /** 判断数据是否存在 */
          let hasActive = false
          if (this.postActive) {
            for (let index = 0; index < this.postList.length; index++) {
              const item = this.postList[index]
              if (item.postId == this.postActive.postId) {
                this.postActive = item
                hasActive = true
                break
              }
            }
          } else {
            this.postActive = this.postList[0]
          }
          this.getPostByRoleList(this.postActive)
          this.postMenuLoading = false
        })
        .catch(() => {
          this.postMenuLoading = false
        })
    },

    /**
     * 关联员工
     */
    addEmployees() {
      this.relateEmpoyeeShow = true
    },

    /**
     * 关联员工确定
     */
    employeesSave(val) {
      this.relateEmpoyeeShow = false
      this.getPostByRoleList(this.postActive)
    },

    /**
     * 删除
     */
    postDelect(val) {
      this.$confirm('此操作将永久删除是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.postLoading = true
          deletePost({
            id: val.postId
          }).then(res => {
            this.postLoading = true
            if (this.postList.length) {
              this.postActive = this.postList[0]
              // 点击角色 复制权限 用于编辑操作
              this.getPostByRoleList(this.postActive)
            }
            this.getPostList()
            this.$message.success('删除成功')
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    /**
     * 新建岗位
     */
    newPostClose() {
      this.newPostVisible = false
    },
    newPostBtn(isRole) {
      this.newPostVisible = true
      this.AssociaRole = []
      if (isRole === 'relatierol') {
        this.postTitle = '关联角色'
      } else {
        this.postTitle = '新建岗位'
        this.post = {}
      }
    },

    /**
     * 岗位操作
     */
    postDropdownClick(value) {
      this.dropdownHandlePost = value
    },
    postHandleClick(command) {
      if (command == 'edit') {
        this.editGetRoleId(this.dropdownHandlePost)
        this.postEditBtn(this.dropdownHandlePost)
      } else if (command == 'delete') {
        this.postDelect(this.dropdownHandlePost)
      }
    },

    /**
     * 角色说明文字
     */
    getReminderContent() {
      if (this.postActive && this.postActive.remark == 'project') {
        return '项目管理员拥有“项目管理”模块所有权限，能看到并维护所有项目信息'
      }
      return ''
    },

    /**
     * 岗位编辑
     */
    postEditBtn(val) {
      this.postTitle = '编辑岗位'
      this.post = {
        title: val.name
      }
      this.newPostVisible = true
    },
    /**
     * 角色删除
     */
    roleDelect(val) {
      this.$confirm('此操作将永久删除是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteRole({ id: val.id }).then(res => {
            this.getPostByRoleList(this.postActive)
            this.$message.success('删除成功')
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    newPostSubmit() {
      if (!this.post.title && this.postTitle != '关联角色') {
        this.$message.error('岗位名称不能为空')
      } else {
        if (this.postTitle == '新建岗位') {
          addAndSetPost({
            name: this.post.title,
            roleIds: this.AssociaRole.join(',')
          }).then(res => {
            this.getPostList()
            this.$message.success('添加成功')
            this.newPostClose()
          })
        } else if (this.postTitle == '编辑岗位') {
          addAndSetPost({
            name: this.post.title,
            postId: this.postActive.postId,
            roleIds: this.AssociaRole.join(',')
          }).then(res => {
            this.getPostList()
            this.$message.success('编辑成功')
            this.newPostClose()
          })
        } else if (this.postTitle == '关联角色') {
          saveModifyPostRole({
            postId: this.postActive.postId,
            roleIds: this.AssociaRole.join(',')
          }).then(res => {
            this.getPostByRoleList(this.postActive)
            this.newPostClose()
          })
        }
      }
    },

    /**
     * 岗位列表点击
     */
    postMenuSelect(val) {
      this.postActive = val

      if (this.mainMenuIndex == 'rule' && !this.showRuleSet) {
        this.mainMenuIndex = 'user'
      }

      this.getPostByRoleList(this.postActive)
    },
    copyItem(array) {
      var temps = []
      for (let index = 0; index < array.length; index++) {
        temps.push(array[index])
      }
      return temps
    },
    removeItem(array, item) {
      var removeIndex = -1
      for (let index = 0; index < array.length; index++) {
        if (item == array[index]) {
          removeIndex = index
          break
        }
      }
      if (removeIndex > 0) {
        array.splice(removeIndex, 1)
      }
    },
    containItem(array, item) {
      for (let index = 0; index < array.length; index++) {
        if (item == array[index]) {
          return true
        }
      }
      return false
    },

    /**
     * 岗位对应的角色列表
     */
    getPostByRoleList(role, noReset) {
      if (!role) {
        return
      }
      if (!noReset) {
        this.currentPage = 1
      }
      this.postLoading = true
      roleByPostId({
        page: this.currentPage,
        limit: this.pageSize,
        id: role.postId
      })
        .then(res => {
          this.tableData = res.data.list
          this.total = res.data.totalRow
          this.postLoading = false
        })
        .catch(() => {
          this.postLoading = false
        })
    },
    /**
     * 更改每页展示数量
     */
    handleSizeChange(val) {
      this.pageSize = val
      this.getPostByRoleList(this.postActive, true)
    },
    /**
     * 更改当前页数
     */
    handleCurrentChange(val) {
      this.currentPage = val
      this.getPostByRoleList(this.postActive, true)
    }
  }
}
</script>

<style lang="scss" scoped>
.post-authorization {
  height: 100%;
  box-sizing: border-box;
  overflow: hidden;
}
.title {
  font-size: 18px;
  height: 40px;
  padding: 0 20px;
  line-height: 40px;
  margin: 10px 0;
  color: #333;
}
.post-box {
  height: calc(100% - 60px);
  overflow: hidden;
  position: relative;
}
.nav {
  width: 200px;
  background: #fff;
  border: 1px solid #e6e6e6;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
.nav-new-btn {
  text-align: center;
  padding-top: 15px;
  padding-bottom: 15px;
}
.nav-new-btn .el-button {
  background: #4ab8b8;
  border-color: #4ab8b8;
  color: #fff;
  width: 140px;
  border-radius: 2px;
}
.content-box {
  background: #fff;
  border: 1px solid #e6e6e6;
  margin-left: 215px;
  height: 100%;
  overflow: hidden;
  padding-top: 10px;
  position: relative;
}
.content-table {
  overflow: hidden;
}
.content-table > .el-button {
  float: right;
  margin-bottom: 15px;
  margin-right: 30px;
}
.content-box .content-table-span {
  color: #3e84e9;
  margin-left: 5px;
  cursor: pointer;
}

.content-table-header {
  padding: 0 15px 5px;
  .content-table-header-reminder {
    flex: 1;
    margin-right: 5px;
  }
}

/* 权限管理 */
.jurisdiction-content {
  height: calc(100% - 61px);
  position: relative;
  overflow: hidden;
}
.content-left {
  height: 100%;
  margin-right: 250px;
  overflow: hidden;
}
.content-right {
  width: 250px;
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
}
.jurisdiction-box {
  padding-bottom: 15px;
  height: calc(100% - 61px);
  overflow: hidden;
  position: relative;
}
.jurisdiction-content-checkbox {
  border-right: 1px dashed #e6e6e6;
  height: calc(100% - 47px);
  overflow-y: scroll;
  padding: 20px;
}
.jurisdiction-content-checkbox
  .el-tree
  /deep/
  .el-tree-node
  > .el-tree-node__content {
  margin-bottom: 20px;
  width: 150px;
}
.jurisdiction-content-checkbox /deep/ .el-tree .el-tree-node {
  white-space: inherit;
  margin-bottom: 5px;
}
.jurisdiction-content-checkbox
  /deep/
  .el-tree
  > .el-tree-node
  > .el-tree-node__children
  > .is-expanded
  > .el-tree-node__children
  > .is-expanded {
  display: inline-block;
}
.post-authorization /deep/ .el-tree-node__expand-icon {
  display: none;
}
.data-radio {
  padding: 5px 30px;
}
.data-radio .el-radio {
  display: block;
  margin: 20px 0;
}
/* 新建角色 */
.input-post {
  padding: 10px 0 20px;
  width: 100%;
}
.el-select.input-post /deep/ .el-select__tags{
  top: 45%;
}
.post-nav-box {
  line-height: 30px;
  overflow-y: auto;
  padding: 5px 0 20px 0;
  height: calc(100% - 105px);
}
.post-nav-box .item-list {
  color: #333;
  font-size: 13px;
  padding-left: 30px;
  height: 40px;
  line-height: 40px;
  border-right: 2px solid transparent;
  cursor: pointer;
  position: relative;
  .icon-close {
    position: absolute;
    top: 0;
    right: 8px;
    z-index: 1;
    display: none;
  }
}
.post-nav-box .item-list:hover {
  background: #ebf3ff;
  border-right-color: #46cdcf;
  .icon-close {
    display: block;
  }
}
.item-list-hover {
  background: #ebf3ff;
  border-right: 2px solid #46cdcf;
}

.post-nav-box .item-list:hover .icon-close {
  display: block;
  float: right;
}
.jurisdiction-edit {
  text-align: right;
  padding: 10px 30px;
  position: absolute;
  top: 0;
  right: 20px;
  z-index: 3;
}

/** 分页布局 */
.p-contianer {
  position: relative;
  background-color: white;
  height: 44px;
  .p-bar {
    float: right;
    margin: 5px 100px 0 0;
    font-size: 14px !important;
  }
}

// .el-tabs /deep/ .el-tabs__nav-wrap::after {
//   display: none !important;
// }

.el-tabs /deep/ .el-tabs__header {
  padding: 0 17px;
  margin: 0 0 15px !important;
}

.el-tabs /deep/ .el-tabs__item {
  font-size: 13px !important;
  height: 40px !important;
  line-height: 40px !important;
}

@import '../styles/table.scss';
</style>
